package com.csot.ry.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.BiMap;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.csot.common.annotation.Log;
import com.csot.common.constant.HttpStatus;
import com.csot.common.core.controller.BaseController;
import com.csot.common.core.domain.AjaxResult;
import com.csot.common.core.domain.entity.SysUser;
import com.csot.common.core.page.TableDataInfo;
import com.csot.common.enums.BusinessType;
import com.csot.common.utils.SecurityUtils;
import com.csot.common.utils.ServletUtils;
import com.csot.common.utils.bean.BeanUtils;
import com.csot.common.utils.poi.ExcelUtil;
import com.csot.model.CityIp;
import com.csot.model.CitySegment;
import com.csot.model.CoarseIp;
import com.csot.ry.domain.TCityIp;
import com.csot.ry.poi.ExcelUtilSub;
import com.csot.ry.service.ITCityIpService;
import com.csot.ry.util.CacheKitUtil;
import com.github.pagehelper.PageInfo;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.ehcache.CacheKit;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 地址ip明细Controller
 *
 * @author LS
 * @date 2022-05-31
 */
@RestController
@RequestMapping("/ipmanagement/cityip")
public class TCityIpController extends BaseController {

    @Autowired
    private ITCityIpService tCityIpService;

    private CityIp cityIp = new CityIp().dao();

    private CoarseIp coarseIp = new CoarseIp().dao();

    static BiMap<String, String> ip_type = CacheKit.get("dict-data", "ip_type");
    static BiMap<String, String> ip_city = CacheKit.get("dict-data", "ip_city");
    static BiMap<String, String> ip_record = CacheKit.get("dict-data", "ip_record");
    static BiMap<String, String> ip_use_type = CacheKit.get("dict-data", "ip_use_type");
    static BiMap<String, String> ip_status = CacheKit.get("dict-data", "ip_status");
//     static BiMap<String, String> ip_dept = CacheKit.get("dict-data", "user-dept");

    /**
     * 查询地址ip明细列表
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:cityip:list')")
    @GetMapping("/list/{type}")
    public TableDataInfo list(TCityIp tCityIp, @PathVariable("type") String type) {
        try {
            startPage();
            List<TCityIp> list = new ArrayList<>();
            SysUser user = SecurityUtils.getLoginUser().getUser();
            Long deptid = user.getDeptId();
            if (deptid != 100) {
                tCityIp.setIpCity(CacheKitUtil.ip_dept.get(user.getDept().getParentId() + ""));
                List<CityIp> cityIpList = cityIp.find("select * from t_city_ip where ip_address = ? and ip_city = ?", tCityIp.getIpAddress(),
                        tCityIp.getIpCity());
                List<CoarseIp> coarseIpList = coarseIp.find("select * from t_coarse_ip where ip_address = ? and ip_city = ?", tCityIp.getIpAddress(),
                        tCityIp.getIpCity());
                for (CityIp ci : cityIpList) {
                    TCityIp tCityIp1 = new TCityIp();
                    BeanUtils.copyProperties(ci, tCityIp1);
                    list.add(tCityIp1);
                }
                for (CoarseIp ci : coarseIpList) {
                    TCityIp tCityIp1 = new TCityIp();
                    BeanUtils.copyProperties(ci, tCityIp1);
                    list.add(tCityIp1);
                }
            } else {
                List<CityIp> cityIpList = cityIp.find("select * from t_city_ip where ip_address = ? ", tCityIp.getIpAddress());
                List<CoarseIp> coarseIpList = coarseIp.find("select * from t_coarse_ip where ip_address = ?", tCityIp.getIpAddress());
                for (CityIp ci : cityIpList) {
                    TCityIp tCityIp1 = new TCityIp();
                    BeanUtils.copyProperties(ci, tCityIp1);
                    list.add(tCityIp1);
                }
                for (CoarseIp ci : coarseIpList) {
                    TCityIp tCityIp1 = new TCityIp();
                    BeanUtils.copyProperties(ci, tCityIp1);
                    list.add(tCityIp1);
                }
            }


            return getDataTable(list);
        } catch (Exception e) {
            List<TCityIp> list = new ArrayList<>();
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setRows(list);
            rspData.setTotal(new PageInfo(list).getTotal());
            rspData.setMsg(e.getMessage());
            return rspData;
        }
    }

    /**
     * 导出地址ip明细列表
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:cityip:export')")
    @Log(title = "地址ip明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export/{type}")
    public void export(HttpServletResponse response, TCityIp tCityIp, @PathVariable("type") String type) {
        //测试更新子表,TotalSegmentDetail好用了之后删除此方法
//        set1();
        String parentId = getLoginUser().getUser().getDept().getParentId() + "";
        if (CacheKitUtil.ip_dept != null && StrUtil.isNotEmpty(parentId)) {
            tCityIp.setIpCity(CacheKitUtil.ip_dept.get(parentId + ""));
        }
        tCityIp.setIpType(type.toLowerCase());
        List<TCityIp> list = tCityIpService.selectTCityIpList(tCityIp);
        ExcelUtil<TCityIp> util = new ExcelUtil<TCityIp>(TCityIp.class);
        for (TCityIp t : list) {
            t.setIpType(ip_type.get(t.getIpType()));
            t.setIpCity(ip_city.get(t.getIpCity()));
            t.setRecordStatus(ip_record.get(t.getRecordStatus()));
            t.setIpStatus(ip_status.get(t.getIpStatus()));
            t.setIpUseType(ip_use_type.get(t.getIpUseType()));
        }
        util.exportExcel(response, list, "地址ip明细数据");
    }

    private void set1() {
        List<CitySegment> csList = getSlot();
        if (CollUtil.isEmpty(csList)) {
            return;
        }

        csList.forEach(f -> {
            ThreadUtil.execute(() -> {
                Db.tx(() -> {
                    List<CityIp> ciList = new ArrayList<>();
                    for (long i = f.getIpStartI(); i <= f.getIpEndI(); i++) {
                        CityIp ci = getTotalIpByAll(f);
//                        BeanUtil.copyProperties(f, ci, "id");
                        ci.setIpAddressI(i);
                        ci.setIpAddress(NetUtil.longToIpv4(i));
                        ciList.add(ci);
                    }
                    Db.batchSave(ciList, ciList.size());
                    return true;
                });
            });
        });
    }

    private CityIp getTotalIpByAll(CitySegment f) {
        CityIp ci = new CityIp();
        ci.setCreateBy(f.getCreateBy());
        ci.setCreateTime(f.getCreateTime());
        ci.setIpCity(f.getIpCity());
        ci.setIpEquipment(f.getIpEquipment());
        ci.setIpGateway(f.getIpGateway());
        ci.setIpManagement(f.getIpManagement());
        ci.setIpSegmentId(f.getId());
        ci.setIpStatus(f.getIpStatus());
        ci.setIpType(f.getIpType());
        ci.setIpUser(f.getIpUser());
        ci.setIpUseType(f.getIpUseType());
        ci.setRecordStatus(f.getRecordStatus());
        ci.setRecordType(f.getRecordType());
        ci.setRemark(f.getRemark());
        ci.setUpdateBy(f.getUpdateBy());
        ci.setUpdateTime(f.getUpdateTime());
        return ci;
    }

    public List<CitySegment> getSlot() {
        // TODO Auto-generated method stub

        CitySegment dao = new CitySegment().dao();
        List<CitySegment> csList = dao
                .find("select * from t_city_segment t where id not IN (select ip_segment_id from t_city_ip)");
        return csList;

    }

    /**
     * 获取地址ip明细详细信息
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:cityip:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tCityIpService.selectTCityIpById(id));
    }

    /**
     * 新增地址ip明细
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:cityip:add')")
    @Log(title = "地址ip明细", businessType = BusinessType.INSERT)
    @PostMapping(value = "/{type}")
    public AjaxResult add(@RequestBody TCityIp tCityIp, @PathVariable("type") String type) {
        tCityIp.setIpType(type.toLowerCase());
        return toAjax(tCityIpService.insertTCityIp(tCityIp));
    }

    /**
     * 修改地址ip明细
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:cityip:edit')")
    @Log(title = "地址ip明细", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/{type}")
    public AjaxResult edit(@RequestBody TCityIp tCityIp, @PathVariable("type") String type) {
        tCityIp.setIpType(type.toLowerCase());
        return toAjax(tCityIpService.updateTCityIp(tCityIp));
    }

    /**
     * 删除地址ip明细
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:cityip:remove')")
    @Log(title = "地址ip明细", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tCityIpService.deleteTCityIpByIds(ids));
    }

    @Log(title = "城市ip导入查询", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('ipmanagement:cityip:importQuery')")
    @PostMapping("/importQuery/{type}")
    public TableDataInfo importQuery(MultipartFile file, boolean updateSupport, @PathVariable("type") String type) throws Exception {
        try {
            HttpSession hs = ServletUtils.getSession();
            ExcelUtilSub<TCityIp> util = new ExcelUtilSub<TCityIp>(TCityIp.class);
            List<TCityIp> tCityIpList = util.importExcel(file.getInputStream());
            for (TCityIp tCityIp : tCityIpList) {
                tCityIp.setIpType("'" + type.toLowerCase() + "'");
            }
            List<TCityIp> list = tCityIpService.TCityIpLists(tCityIpList);
            hs.setAttribute("ipmanagement:cityip:importQuery", list);
            return super.getDataTable(list);
        } catch (Exception e) {
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("查询失败");
            rspData.setRows(null);
            rspData.setTotal(0);
            return rspData;
        }
    }

    /**
     * 导出城市ip段列表
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:cityip:exportQuery')")
    @Log(title = "城市ip导出查询", businessType = BusinessType.EXPORT)
    @PostMapping("/exportQuery")
    public void exportQuery(HttpServletResponse response) {
        List<TCityIp> result = new ArrayList<>();
        HttpSession hs = ServletUtils.getSession();
        Object obj = hs.getAttribute("ipmanagement:cityip:importQuery");
        if (Objects.nonNull(obj)) {
            if (obj instanceof List) {
                result = (List) obj;
            }
        }
        for (TCityIp t : result) {
            t.setIpType(CacheKitUtil.ip_type.get(t.getIpType()));
            t.setIpCity(CacheKitUtil.ip_city.get(t.getIpCity()));
            t.setRecordStatus(CacheKitUtil.ip_record.get(t.getRecordStatus()));
            t.setIpStatus(CacheKitUtil.ip_status.get(t.getIpStatus()));
            t.setIpUseType(CacheKitUtil.ip_use_type.get(t.getIpUseType()));
            t.setAddressStatus(CacheKitUtil.address_status.get(t.getAddressStatus()));
            t.setRecordType(CacheKitUtil.record_type.get(t.getRecordType()));
        }
        ExcelUtilSub<TCityIp> util = new ExcelUtilSub<TCityIp>(TCityIp.class);
        util.exportExcel(response, result, "地市ip查询数据");

    }

    @PostMapping("/importTemplateq")
    public void importTemplateq(HttpServletResponse response) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        try {
            String path = System.getProperty("user.dir");
            path = path + File.separator + "Template" + File.separator + "ipquery.xlsx";
            IOUtils.write(Files.readAllBytes(Paths.get(path)), response.getOutputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.error("下载ip段模块异常", e);
        }
    }

}
